<?php
namespace app\framework\lib;
use app\model\ConfigModel;
class Dict {

    public static $config =[];
    public static $instance =null;
    public static  function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public  static function init(){
        $map    = array('status' => 1);
        $dictModel = new ConfigModel();
        $data = $dictModel->where($map)->field("type,name,value")->select()->toArray();
        $config = array();
        if($data && is_array($data)){
            foreach ($data as $value) {
                $config[strtolower($value['name'])] = self::parse($value['type'], $value['value']);
            }
        }
        self::$config = $config;
        return $config;
    }

    /**
     * 根据配置类型解析配置
     * @param  integer $type  配置类型
     * @param  string  $value 配置值
     */
    private static function parse($type, $value){
        switch ($type) {
            case 3: //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if(strpos($value,':')){
                    $value  = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val);
                        $value[$k]   = $v;
                    }
                }else{
                    $value =    $array;
                }
                break;
        }
        return $value;
    }
    public function __get($name)
    {
        return self::$config[$name] ?? null;
    }

    public function __set($name,$value)
    {
        return self::$config[$name] = $value;
    }
}
